//
//  EditWantJobViewController.m
//  XingHeHuiJu
//
//  Created by 于顺燊 on 2018/11/15.
//  Copyright © 2018年 cywkj. All rights reserved.
//

#import "EditWantJobViewController.h"
#import "JobCategoryInfo.h"
#import "BRPickerView.h"

@interface EditWantJobViewController ()<UITextViewDelegate, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource>

@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) NSMutableArray *jobCategoryInfoArr;
@property (strong, nonatomic) UIPickerView *categoryPicker;
@property (nonatomic, strong) NSString *jobCategoryStr;
@property (strong, nonatomic) UIView *pickerBgView;
@property (strong, nonatomic) UIView *pickerToolbgView;
/** 当前选中的职位ID */
@property (strong, nonatomic) NSString *selectedCategoryID;
@property (strong, nonatomic) NSString *selectedJobWantStateID;

@end

@implementation EditWantJobViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	[self getCategory];
	[self createUI];
}

- (void)createUI {
	self.navigationItem.title = @"修改求职意向";
	
	_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
	_scrollView.backgroundColor = UISeparatedColorRGB;
	[self.view addSubview:_scrollView];
	NSArray *arr = [NSArray arrayWithObjects:@"   求职状态*", @"   期望职位*", @"   薪资要求*", nil];
	CGSize size = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(15)];
	
	for (int i = 0; i < arr.count; i++) {
		UILabel *label = [[UILabel alloc] init];
		[_scrollView addSubview:label];
		label = [self createLabel:label text:arr[i]];
		label.tag = 1+i;
	}
	
	
	UILabel *jobWantStateL = [self.view viewWithTag:1];
	jobWantStateL.frame = CGRectMake(0, 0, SCREEN_WIDTH, size.height+30);
	UITextField *jobWantStateTF = [self createTextFieldWith:jobWantStateL tag:11 pickerNum:0];
	self.selectedJobWantStateID = self.model.apply_status;
	if ([self.model.apply_status isEqualToString:@"0"]) {
		jobWantStateTF.text = @"已离职";
	}
	else {
		jobWantStateTF.text = @"在职";
	}
	NSDictionary *jobWantStateDict = @{
									   @"0":@"已离职",
									   @"1":@"在职"
									   };
	
	__weak UITextField *weakTf1 = jobWantStateTF;
	[jobWantStateTF addActionWithblock:^{
		[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
		NSArray *jobWantStateName = [jobWantStateDict allValues];
		[BRStringPickerView showStringPickerWithTitle:@"选择求职状态" dataSource:jobWantStateName defaultSelValue:nil isAutoSelect:NO themeColor:UIMainColorRGB resultBlock:^(id selectValue) {
			weakTf1.text = selectValue;
			[jobWantStateDict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
				if ([obj isEqualToString:selectValue]) {
					self.selectedJobWantStateID = key;
				}
			}];
		}];
	}];
	
	UILabel *wantCategoryL = [self.view viewWithTag:2];
	wantCategoryL.frame = CGRectMake(0, jobWantStateL.y+jobWantStateL.height+1, SCREEN_WIDTH, size.height+30);
	UITextField *wantCategoryTF = [self createTextFieldWith:wantCategoryL tag:12 pickerNum:0];
	self.selectedCategoryID = self.model.category_id;
	wantCategoryTF.text = self.model.category_title;
	[wantCategoryTF addActionWithblock:^{
		[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
		[self pickerShow:1];
	}];
	
	UILabel *salaryL = [self.view viewWithTag:3];
	salaryL.frame = CGRectMake(0, wantCategoryL.y+wantCategoryL.height+1, SCREEN_WIDTH, size.height+30);
	UITextField *salaryTF = [self createTextFieldWith:salaryL tag:13 pickerNum:0];
	NSArray *salaryArr = @[@"2000以下", @"2k-4k", @"4k-6k", @"6k-8k", @"8k-10k", @"10k-15k", @"15k-20k", @"20k-30k", @"30k-40k", @"40k-50k", @"5万以上"];
	__weak UITextField *weakTf2 = salaryTF;
	salaryTF.text = self.model.salary;
	[salaryTF addActionWithblock:^{
		[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
		[BRStringPickerView showStringPickerWithTitle:@"选择期望薪资" dataSource:salaryArr defaultSelValue:nil isAutoSelect:NO themeColor:UIMainColorRGB resultBlock:^(id selectValue) {
			weakTf2.text = selectValue;
		}];
	}];
	
	//初始化PickerView相关组件
	_pickerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
	[self.view addSubview:_pickerBgView];
	_pickerBgView.backgroundColor = RGBA(0, 0, 0, 0.2);
	_pickerBgView.hidden = YES;
	
	_categoryPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 2*SCREEN_HEIGHT, SCREEN_WIDTH, SH(3)+64)];
	[self.view addSubview:_categoryPicker];
	_categoryPicker.delegate = self;
	_categoryPicker.dataSource = self;
	_categoryPicker.backgroundColor = UISeparatedColorRGB;
	_categoryPicker.showsSelectionIndicator = YES;
	_categoryPicker.hidden = YES;
	
	_pickerToolbgView = [[UIView alloc] initWithFrame:CGRectMake(0, 2*SCREEN_HEIGHT, SCREEN_WIDTH, 40)];
	[self.view addSubview:_pickerToolbgView];
	_pickerToolbgView.backgroundColor = UISeparatedColorRGB;
	
	NSArray *arr2 = @[@"取消", @"确定"];
	for (int i = 0; i < arr2.count; i++) {
		UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_pickerToolbgView addSubview:btn];
		[btn setTitle:arr2[i] forState:UIControlStateNormal];
		[btn setTitleColor:kBlackColor forState:UIControlStateNormal];
		btn.titleLabel.font = kUHSystemFontWithSize(12);
		if (i==0) {
			btn.frame = CGRectMake(0, 0, 50, 40);
			[btn addTarget:self action:@selector(pickerRemove) forControlEvents:UIControlEventTouchUpInside];
		}
		else {
			btn.frame = CGRectMake(SCREEN_WIDTH-50, 0, 50, 40);
			[btn addTarget:self action:@selector(priceBtnText) forControlEvents:UIControlEventTouchUpInside];
		}
	}
	UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 39, SCREEN_WIDTH, 1)];
	[_pickerToolbgView addSubview:line];
	line.backgroundColor = kLightGrayColor;
	
	//保存按钮
	UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake( 30, salaryL.y+salaryL.height+20,  SCREEN_WIDTH-30*2, 40)];
	saveBtn.layer.cornerRadius = saveBtn.height/4;
	[saveBtn setTitle:@"保存" forState:UIControlStateNormal];
	[saveBtn setBackgroundColor:UIMainColorRGB];
	[saveBtn addTarget:self action:@selector(completeAction) forControlEvents:UIControlEventTouchUpInside];
	[_scrollView addSubview:saveBtn];
	_scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, saveBtn.y+saveBtn.height+20);
}

#pragma mark ==========UIPickerView==========
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
	return 2;
}
//UIPickerViewDataSource中定义的方法，该方法的返回值决定该控件指定列包含多少个列表项
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	// 由于该控件只包含一列，因此无须理会列序号参数component
	// 该方法返回books.count，表明books包含多少个元素，该控件就包含多少行
	//    return self.pickerArr.count;
	if([pickerView isEqual:_categoryPicker]){
		if (component == 0) {
			return self.jobCategoryInfoArr.count;
		}
		else {
			
			if (self.jobCategoryInfoArr.count) {
				JobCategoryInfo *model = self.jobCategoryInfoArr[[pickerView selectedRowInComponent:0]];
				NSArray *array = model.child;
				if (array != nil && ![array isKindOfClass:[NSNull class]] && array.count != 0) {
					return array.count;
				}
				else{
					return 0;
				}
			}
			else{
				return 0;
			}
		}
	}
	else {
		return 0;
	}
}
// UIPickerViewDelegate中定义的方法，该方法返回的NSString将作为UIPickerView
// 中指定列和列表项的标题文本
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	// 由于该控件只包含一列，因此无须理会列序号参数component
	// 该方法根据row参数返回books中的元素，row参数代表列表项的编号，
	// 因此该方法表示第几个列表项，就使用books中的第几个元素
	//    return [self.pickerArr objectAtIndex:row];
	
	if([pickerView isEqual:_categoryPicker]) {
		if (component == 0) {
			JobCategoryInfo *model = self.jobCategoryInfoArr[row];
			return model.title;
		} else {
			JobCategoryInfo *model = self.jobCategoryInfoArr[[pickerView selectedRowInComponent:0]];
			NSArray *array = model.child;
			if (array != nil && ![array isKindOfClass:[NSNull class]] && array.count != 0 && array.count >= row+1) {
				return [array[row] objectForKey:@"title"];
			}
			else {
				return @"";
			}
		}
	}
	else{
		return @"";
	}
}
// 当用户选中UIPickerViewDataSource中指定列和列表项时激发该方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	//    [_priceSortedBtn setTitle:self.pickerArr[row] forState:UIControlStateNormal];
	//    self.pickerStr = self.pickerArr[row];
	if ([pickerView isEqual:_categoryPicker]) {
		
		[pickerView reloadComponent:1];
		[pickerView reloadComponent:0];
	}
}

- (void)priceBtnText {
	
	if(_categoryPicker.isHidden == NO) {
		JobCategoryInfo *parent = self.jobCategoryInfoArr[[_categoryPicker selectedRowInComponent:0]];
		NSArray *children = parent.child;
		if (children != nil && ![children isKindOfClass:[NSNull class]] && children.count != 0)
		{
			self.jobCategoryStr = children[[_categoryPicker selectedRowInComponent:1]][@"title"];
			self.selectedCategoryID = children[[_categoryPicker selectedRowInComponent:1]][@"id"];
			UITextField *textField = (UITextField *)[self.view viewWithTag:12];
			textField.text = self.jobCategoryStr;
			NSLog(@"the selected jobID is %@", self.selectedCategoryID);
		}
		//如果没有子分类就用父级的信息
		else {
			self.jobCategoryStr = parent.title;
			self.selectedCategoryID = parent.cateId;
			UITextField *textField = (UITextField *)[self.view viewWithTag:12];
			textField.text = self.jobCategoryStr;
			NSLog(@"the selected jobID is %@", self.selectedCategoryID);
		}
		
		[self pickerRemove];
	}
}

- (void)pickerShow:(NSInteger)picker {
	
	[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
	
	if(picker == 1){
		[self getCategory];
		_categoryPicker.hidden = NO;
		_pickerBgView.hidden = NO;
		[UIView animateWithDuration:0.33 animations:^{
			_categoryPicker.y = SH(3)*2-64;
			_pickerToolbgView.y = _categoryPicker.y-40;
		} completion:^(BOOL finished) {
		}];
	}
}
- (void)pickerRemove {
	
	[UIView animateWithDuration:0.33 animations:^{
		_pickerToolbgView.y = 2*SCREEN_HEIGHT;
		_categoryPicker.y = 2*SCREEN_HEIGHT;
	} completion:^(BOOL finished) {
		_pickerBgView.hidden = YES;
		_categoryPicker.hidden = YES;
	}];
}

- (UILabel *)createLabel:(UILabel *)label text:(NSString *)text {
	
	label.textColor = [UIColor grayColor];
	label.text = text;
	label.font = kUHSystemFontWithSize(15);
	label.backgroundColor = kWhiteColor;
	return label;
}

- (UITextView *)createTextViewWith:(UILabel *)label tag:(NSInteger)tag heightFactor:(CGFloat)heightFactor
{
	UITextView *textView = [[UITextView alloc] init];
	[_scrollView addSubview:textView];
	textView.textColor = [UIColor lightGrayColor];
	textView.font = kUHSystemFontWithSize(14);
	textView.delegate = self;
	[textView scrollRangeToVisible:NSMakeRange(0,1)];
	CGSize signSize = [textView sizeThatFits:CGSizeMake(SCREEN_WIDTH-20-SW(20), MAXFLOAT)];
	textView.frame = CGRectMake(0, label.y+label.height+1, SCREEN_WIDTH, 15+signSize.height*heightFactor);
	textView.textContainerInset = UIEdgeInsetsMake(15, SW(20), 15, 20);//设置页边
	textView.tag = tag;
	return textView;
}

- (UITextField *)createTextFieldWith:(UILabel *)label tag:(NSInteger)tag pickerNum:(NSInteger)picker
{
	CGSize size = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(15)];
	UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(30+size.width, label.y, SCREEN_WIDTH-(50+size.width), size.height+30)];
	[_scrollView addSubview:textField];
	textField.delegate = self;
	textField.textColor = kGrayColor;
	textField.clearButtonMode = UITextFieldViewModeWhileEditing;
	textField.font = kUHSystemFontWithSize(15);
	textField.textAlignment = NSTextAlignmentRight;
	textField.rightViewMode = UITextFieldViewModeAlways;
	textField.tag = tag;
	UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.height/2, size.height)];
	textField.rightView = imgV;
	imgV.image = IMAGE(@"arrow_right_grey");
	
	if (picker!=0) {
		UIView *view = [[UIView alloc] initWithFrame:CGRectMake(textField.x, textField.y, textField.width, textField.height)];
		[_scrollView addSubview:view];
		[view addActionWithblock:^{
			NSLog(@"选择器%ld",picker);
			[self pickerShow:picker];
		}];
	}
	return textField;
}

- (void)getCategory {
	
	[[NetworkTool sharedTool] requestWithName:@"获取职位分类列表" URLString:APIRecruitCategoryList parameters:nil method:@"GET" callBack:^(id responseObject) {
		
		NSArray *arr = responseObject[@"data"];
		[_jobCategoryInfoArr removeAllObjects];
		for (NSDictionary *dict in arr)
		{
			JobCategoryInfo *model = [[JobCategoryInfo alloc] init];
			[model setValuesForKeysWithDictionary:dict];
			[_jobCategoryInfoArr addObject:model];
		}
		
		[_categoryPicker reloadComponent:0];
		[_categoryPicker reloadComponent:1];
		
	}];
}

- (void)completeAction {
	
	UITextField *salaryTF = [self.view viewWithTag:13];
	
	NSDictionary *paramDict = @{
								@"resume_id":self.model.resumeId,
								@"title":self.model.title,
								@"name":self.model.name,
								@"head_img":self.model.head_img,
								@"category_id":self.selectedCategoryID,
								@"salary":salaryTF.text,
								@"education":self.model.education,
								@"mobile":self.model.mobile,
								@"email":self.model.email,
								@"work_life":self.model.work_life,
								@"apply_status":self.selectedJobWantStateID
								};
	
	[[NetworkTool sharedTool] requestWithName:@"更新求职状态" URLString:APIUpdateResume parameters:paramDict method:@"POST" callBack:^(id responseObject) {
		NSString *resultState = responseObject[@"data"][@"status"];
		NSString *message = responseObject[@"data"][@"message"];
		if ([resultState integerValue] == 1) {
			UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
			[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				
				[self.navigationController popViewControllerAnimated:YES];
			}]];
			[self presentViewController:alert animated:YES completion:nil];
		}
		else {
			[self presentViewController:[LZCTools alertMessage:@"您没有修改任何东西"] animated:YES completion:nil];
		}
	}];
}

- (NSMutableArray *)jobCategoryInfoArr
{
	if (!_jobCategoryInfoArr) {
		_jobCategoryInfoArr = [[NSMutableArray alloc] init];
	}
	return _jobCategoryInfoArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
